package com.wondersgroup.controller;

import com.wondersgroup.aop.Submit;
import com.wondersgroup.entity.Record;
import com.wondersgroup.entity.User;
import com.wondersgroup.service.RecordService;
import com.wondersgroup.service.UserService;
import com.wondersgroup.util.HttpServletRequestUtil;
import com.wondersgroup.util.PageCalculaterUtil;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {


  @Autowired
  private RecordService recordService;

  @Autowired
  private UserService userService;

  @Submit
  @RequestMapping("/login")
  public Map<String,Object>login(HttpServletRequest request){
    Map<String,Object> map = new HashMap<>();
    JSONObject  json = JSONObject.fromObject(request.getParameter("param"));
    String username = json.getString("username");
    String password = json.getString("password");
    /*String username = HttpServletRequestUtil.getString(request,"username");
    String password = HttpServletRequestUtil.getString(request,"password");*/
    if(username == null || password == null){
      map.put("code",500);
      map.put("msg","参数不能为空！");
      return map;
    }
    User u = userService.login(username,password);
    if(u!=null){
      map.put("code",200);
      map.put("user",u);
    }else{
      map.put("code",500);
      map.put("msg","登录失败！");
    }
    return  map;
  }


  /**
   * 查询全部记录  分页 可按照单位查全部访问记录
   *
   * @return
   */
  @RequestMapping("/getRecordsByCompany")
  public Map<String, Object> getRecords(HttpServletRequest request) {
    Map<String, Object> map = new HashMap<String, Object>();
    //TODO 参数校验
    String dwid = request.getParameter("dwid") != null ? request.getParameter("dwid") : null;
    int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex");
    int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
    System.out.println("pageIndex..."+pageIndex+": "+pageSize);
    int rowIndex = PageCalculaterUtil.getRowIndex(pageIndex, pageSize);
    List<Record> recordList = null;
    try {
      recordList = recordService.getRecordsByCompany(dwid, rowIndex, pageSize);
      map.put("code", 200);
      map.put("recordList", recordList);
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "获取异常！");
    }
    return map;
  }


  @RequestMapping("/export")
  public void export(HttpServletRequest request, HttpServletResponse response) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dwid  = request.getParameter("dwid") != null ? request.getParameter("dwid") : null ;
    OutputStream out = null;
    String fileName = "访客记录表.xls";
    if(dwid!=null){
      fileName = dwid+"_"+fileName;
    }
    try {
      //条件获取 数据
      List<Record> recordList =recordService.getCompanyRecords(dwid);
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet sheet = wb.createSheet("访客记录");
      HSSFCellStyle cellStyle = wb.createCellStyle();
      cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
      cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
      //设置表头
      HSSFRow r  = sheet.createRow(0);
      r.createCell(0).setCellValue("访问单位");
      r.createCell(1).setCellValue("手机号");
      r.createCell(2).setCellValue("姓名");
      r.createCell(3).setCellValue("性别");
      r.createCell(4).setCellValue("证件类型");
      r.createCell(5).setCellValue("证件号码");
      r.createCell(6).setCellValue("体温(℃)");
      r.createCell(7).setCellValue("来访事由");
      r.createCell(8).setCellValue("来访事由其他");
      r.createCell(9).setCellValue("同行人数");
      r.createCell(10).setCellValue("备注");
      r.createCell(11).setCellValue("签到时间");
      r.createCell(12).setCellValue("签退时间");
      if(recordList!=null &&recordList.size()>0){
        for (int i = 0; i < recordList.size(); i++) {
            HSSFRow row = sheet.createRow(i+1);
            Record re = recordList.get(i);
          System.out.println(re.toString());
            // 创建HSSFCell对象 设置单元格的值
            row.createCell(0).setCellValue(re.getDwid()!=null? re.getDwid() : "");
            row.createCell(1).setCellValue(re.getSjhm()!=null? re.getSjhm() : "");
            row.createCell(2).setCellValue(re.getXm() !=null? re.getXm(): "");
            //性别转换
            if(re.getXb()==null){
              row.createCell(3).setCellValue("");
            }else if(re.getXb().equals("1")){
              row.createCell(3).setCellValue("男");
            }else if(re.getXb().equals("2")){
              row.createCell(3).setCellValue("女");
            }else{
              row.createCell(3).setCellValue("未知");
            }
            row.createCell(4).setCellValue(re.getZjlx() != null ? re.getZjlx() : "");
            row.createCell(5).setCellValue(re.getZjhm() != null ? re.getZjhm() : "");
            //体温转换
            row.createCell(6).setCellValue(re.getTw() ==0.0 ? "" :re.getTw()+"");
            row.createCell(7).setCellValue(re.getLfsy() != null ? re.getLfsy() : "");
            row.createCell(8).setCellValue(re.getLfsyqt() != null ? re.getLfsyqt() : "");
            row.createCell(9).setCellValue(re.getTxrs() != 0 ? re.getTxrs() : 0);
            row.createCell(10).setCellValue(re.getBz() != null ? re.getBz() : "");
            if(re.getDjsj()==null){
              row.createCell(11).setCellValue("");
            }else{
              row.createCell(11).setCellValue(sdf.format(re.getDjsj()));
            }
            if(re.getQtsj()==null){
              row.createCell(12).setCellValue("");
            }else{
              row.createCell(12).setCellValue(sdf.format(re.getQtsj()));
            }

        }
      }
      out = response.getOutputStream();
      response.reset();
      response.setHeader("Content-Disposition",
        "attchement;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
      response.setContentType("application/msexcel");
      wb.write(out);
    } catch (Exception e) {
      e.printStackTrace();
      try {
        if (out != null) {
          out.close();
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
}


  public static void main(String[] args) {
    String str = "{\"id\":\"75\",\"shoppingCartItemList\":[{\"id\":\"407\",\"num\":\"10\"}]}";
    JSONObject jsonObject = JSONObject.fromObject(str);
    System.out.println("jsonObject:"+jsonObject);
    String  id = jsonObject.getString("id");
    System.out.println("id:"+id);
  }
}
